<template>
    <div class="app-container">
        <!-- 周基本信息标题 -->
        <el-row :gutter="20" class="mb20" style="margin-top:10px">
            <el-col class="header-title">
                <i class="el-icon-s-order"></i>
                <span>本周基本信息</span>
            </el-col>
            <el-col class="header-item">
                <span>当前处于：</span>
                <el-cascader v-model="treeValue" :options="treeList" :props="{ expandTrigger: 'hover',children:'children',label:'name',value:'id' }" @change="handleChange" size="small" style="width:220px" ref="cascaderCurrent"></el-cascader>
            </el-col>
        </el-row>
        <!-- 周基本信息内容 -->
        <el-card class="mb20" shadow="hover">
            <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="68px" v-loading="weekLoading">
                <el-form-item label="周型" prop="type" :formatter="typeFormat">
                    <el-select v-model="form.type" placeholder="请选择周型" clearable size="small">
                        <el-option v-for="dict in typeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="训练地点" prop="trainingLocationId">
                    <el-select v-model="form.trainingLocationId" placeholder="请输入训练地点" clearable size="small">
                        <el-option v-for="dict in trainingLocationList" :key="dict.id" :label="dict.venue" :value="dict.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="领队" prop="teamLeader">
                    <el-select v-model="form.teamLeader" placeholder="请选择领队" clearable size="small">
                        <el-option v-for="dict in sysUserList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="主教练" prop="headCoach">
                    <el-select v-model="form.headCoach" placeholder="请选择主教练" clearable size="small">
                        <el-option v-for="dict in sysUserList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="专项教练" prop="specialCoach">
                    <el-select v-model="form.specialCoach" placeholder="请选择专项教练" clearable size="small">
                        <el-option v-for="dict in sysUserList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="体能教练" prop="fitnessCoach">
                    <el-select v-model="form.fitnessCoach" placeholder="请选择体能教练" clearable size="small">
                        <el-option v-for="dict in sysUserList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="队医" prop="teamDoctor">
                    <el-select v-model="form.teamDoctor" placeholder="请选择队医" clearable size="small">
                        <el-option v-for="dict in sysUserList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间" prop="startTime" style="width: 400px">
                    <el-date-picker clearable size="small" style="width: 150px" v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择开始时间" readonly>
                    </el-date-picker>
                    <span>至</span>
                    <el-date-picker clearable size="small" style="width: 150px" v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择结束时间" readonly>
                    </el-date-picker>
                </el-form-item>
                <!-- 保存按钮 -->
                <el-form-item style="width: 100px">
                    <el-button type="primary" class="saveBtn" @click="submitForm">保存</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 日计划标题 -->
        <el-row class="mb20" style="margin-top:35px">
            <el-col class="header-title">
                <i class="el-icon-s-order"></i>
                <span>计划日训练</span>
            </el-col>
            <el-col class="header-item header-item2">
                <span>选择日期：</span>
                <span>{{dayQueryParams.day}}</span>
            </el-col>
            <el-col class="header-week">
                <el-radio-group v-model="radio" class="mb20">
                    <el-radio :label="index" v-for="(item,index) in zhouList" :key="index" @change="selectDay">{{item}}</el-radio>
                </el-radio-group>
            </el-col>
            <el-col class="header-item" style="float:right">
                <span>导入历史周计划：</span>
                <el-cascader v-model="modelValue" :options="importTreeList" :props="{ expandTrigger: 'hover',children:'children',label:'name',value:'id' }" @change="handleChangeImport" style="width:220px" size="small" ref="cascaderHistory"></el-cascader>
            </el-col>
        </el-row>

        <!-- 新增按钮和删除按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['training:trainingDay:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['training:trainingDay:remove']">删除
                </el-button>
            </el-col>
        </el-row>
        <!-- 日计划表格列表 -->
        <el-table v-loading="loading" :data="trainingDayList" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="日期" align="center" prop="day" />
            <!-- <el-table-column label="序号" width="100px" align="center" type="index"></el-table-column> -->
            <el-table-column prop="fourSeasons" label="四时" align="center" :formatter="fourSeasonsFormat"></el-table-column>
            <el-table-column prop="firstLevel" label="一级科目" align="center" :formatter="firstLevelFormat"></el-table-column>
            <el-table-column prop="secondLevelName" label="二级科目" align="center"></el-table-column>
            <el-table-column label="时间区间" align="center">
                <template slot-scope="scope">
                    <span>{{scope.row.startTime}}~{{scope.row.endTime}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="realClassHour" label="计划课时数(分钟)" align="center"></el-table-column>
            <el-table-column label="课时完成度(分钟)" align="center">
                <template slot-scope="scope">
                    <span>{{scope.row.realClassHour*scope.row.completion}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button size="small" type="text">
                        <router-link v-if="scope.row.firstLevel==='special_training_water'" :to="{path:'/plan/trainingAchievement_water',query:{row:scope.row}}" class="link-type">
                            <span>查看成绩</span>
                        </router-link>
                        <router-link v-else-if="scope.row.firstLevel==='land_specific_training_dynamometer'" :to="{path:'/plan/trainingAchievement',query:{row:scope.row}}" class="link-type">
                            <span>查看成绩</span>
                        </router-link>
                        <!-- <router-link v-if="scope.row.firstLevel==='d'" :to="'/plan/trainingGroupChannel?groupId='+ scope.row.id" class="link-type">
                            <span>查看成绩</span>
                        </router-link> -->
                    </el-button>
                    <el-button v-if="scope.row.firstLevel==='special_training_water' || scope.row.firstLevel==='land_specific_training_dynamometer'" size="small" type="text" class="link-type" @click="handleSee(scope.row)">航道信息</el-button>
                    <el-button v-if="scope.row.firstLevel==='land_strength_training'" size="small" type="text" class="link-type" @click="handleCourse(scope.row)">课程要求</el-button>
                    <el-button size="small" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['training:trainingWeek:edit']">编辑</el-button>
                    <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['training:trainingDay:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getTrainingDayList" /> -->

        <!-- 查看小组航道信息 -->
        <groupChannelDialog @close="closeDialog" :groupChannelDialogVisible="groupChannelDialogVisible" ref="groupChannelRef"></groupChannelDialog>
        <!-- 陆上身体素质训练课程要求弹框 -->
        <courseRequireDialog @close="closeDialog" :courseRequireDialogVisible="courseRequireDialogVisible" ref="courseRequireRef"></courseRequireDialog>
        <!-- 新增或修改训练科目弹框 -->
        <trainingProjectDialog @close="closeDialog" @submitProject="sendProject" :projectDialogVisible="projectDialogVisible" ref="trainingProjectRef"></trainingProjectDialog>
    </div>
</template>

<script>
import { listTrainingWeek, listGetSysUser, listGetAnnualPlan, getTrainingWeek, delTrainingWeek, addTrainingWeek, updateTrainingWeek, exportTrainingWeek, getNaturalYearTree, importTrainingWeek } from "@/api/training/trainingWeek";
import { listLocation } from "@/api/training/trainingLocation";
import { listTrainingDay, listWeekName, getTrainingDay, delTrainingDay, addTrainingDay, updateTrainingDay, exportTrainingDay, getTrainingDayInfo } from "@/api/training/trainingDay";
import { listTrainingGroup, getTrainingGroup, delTrainingGroup, addTrainingGroup, updateTrainingGroup, exportTrainingGroup } from "@/api/training/trainingGroup";

import groupChannelDialog from "./components/groupChannelDialog.vue";
import trainingProjectDialog from "./components/trainingProjectDialog.vue";
import courseRequireDialog from "./components/courseRequireDialog.vue";
// import eventBus from "@/components/eventBus.js";


export default {
    name: "TrainingWeek",
    components: {
        groupChannelDialog,
        trainingProjectDialog,
        courseRequireDialog
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            weekLoading: true,
            // 是否显示日训练新增或修改对话框
            // trainingDayDialogVisible: false,
            // 是否显示trainingProject弹框
            projectDialogVisible: false,
            groupChannelDialogVisible: false,
            courseRequireDialogVisible: false,
            queryParams: {
                weekId: '' // 周id
            },
            treeValue: [],
            modelValue: [],
            //年/期/周三级联动集合
            treeList: [],
            // 导入周计划模板
            importTreeList: [],
            // 周集合
            typeList: [],
            //训练地点集合
            trainingLocationList: [],
            //用户名称集合
            sysUserList: [],
            // 表单参数
            form: {
                type: '', // 周型
                trainingLocationId: '', // 训练地点
                teamLeader: '', // 领队
                headCoach: '',  // 主教练
                specialCoach: '', // 专项教练
                fitnessCoach: '', // 体能焦虑
                teamDoctor: '', // 对医
                startTime: '',  // 开始日期
                endTime: ''  //  结束日期
            },
            // 表单校验
            rules: {
                annualPlanId: [
                    { required: true, message: "周期名称不能为空", trigger: "blur" },
                ],
            },
            // 以下是日训练列表的一些数据
            // 日训练列表
            trainingDayList: [],
            // 日训练trainingDay查询参数
            dayQueryParams: {
                // pageNum: 1,
                // pageSize: 10,
                weekId: '',
                day: '',
                trainingMode: '-1',
                // firstLevel: ''
            },
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 四时
            fourSeasonsList: [],
            firstLevelOptions: [],
            radio: 0,
            dateList: [],
            zhouList: [],
        }
    },
    watch: {
        // 监听周id
        queryParams: {
            handler(newVal, oldVal) {
                this.getTrainingWeekDetails();
                this.importTreeList = this.treeList
                this.dayQueryParams.weekId = this.queryParams.weekId
            },
            deep: true,
            immediate: true
        },
    },
    created() {
        this.getNaturalYearTreeList();
        this.getWeekTypeList();
        this.getTrainingLocationList();
        this.getSysUserList();
        this.getTrainingDayList();
        // this.getTrainingDayDetails();
        //一级训练项目字典
        this.getDicts("four_time").then(response => {
            this.fourSeasonsList = response.data;
        });
        this.getDicts("first_level").then(response => {
            this.firstLevelOptions = response.data;
        });
    },
    methods: {
        // 根据起始日获取日期数组
        getBetweenDateStr(start, end) {
            var result = [];
            var beginDay = start.split("-");
            var endDay = end.split("-");
            var diffDay = new Date();
            var dateList = new Array();
            var i = 0;
            diffDay.setDate(beginDay[2]);
            diffDay.setMonth(beginDay[1] - 1);
            diffDay.setFullYear(beginDay[0]);
            result.push(start);
            while (i == 0) {
                var countDay = diffDay.getTime() + 24 * 60 * 60 * 1000;
                diffDay.setTime(countDay);
                dateList[2] = diffDay.getDate();
                dateList[1] = diffDay.getMonth() + 1;
                dateList[0] = diffDay.getFullYear();
                if (String(dateList[1]).length == 1) {
                    dateList[1] = "0" + dateList[1];
                }
                if (String(dateList[2]).length == 1) {
                    dateList[2] = "0" + dateList[2];
                }
                result.push(dateList[0] + "-" + dateList[1] + "-" + dateList[2]);
                if (
                    dateList[0] == endDay[0] &&
                    dateList[1] == endDay[1] &&
                    dateList[2] == endDay[2]
                ) {
                    i = 1;
                }
            }
            return result;
        },
        // 根据日期查询周几
        getWeek(dateString) {
            var dateArray = dateString.split("-");
            var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
            return "周" + "日一二三四五六".charAt(date.getDay());
        },
        // 根据日期数组获取zhouList
        getZhouList() {
            const array = []
            for (let i in this.dateList) {
                array.push(this.getWeek(this.dateList[i]));
            }
            this.zhouList = array
        },
        // 接收子组件保存训练项目事件，同时控制dialog弹框的不显示
        sendProject() {
            this.getTrainingDayList()
            this.projectDialogVisible = false
        },
        // 控制dialog弹框不显示
        closeDialog() {
            this.groupChannelDialogVisible = false
            this.projectDialogVisible = false
            this.courseRequireDialogVisible=false
        },
        // 一级科目字典翻译
        firstLevelFormat(row, column) {
            return this.selectDictLabel(this.firstLevelOptions, row.firstLevel);
        },
        // 四时字典翻译
        fourSeasonsFormat(row, column) {
            return this.selectDictLabel(this.fourSeasonsList, row.fourSeasons);
        },
        // 当前处于：级联选择事件
        handleChange(value) {
            this.queryParams.weekId = value[2]
            // this.dayQueryParams.weekId=value[2]
        },
        // 选择某一天
        selectDay(index) {
            this.dayQueryParams.day = this.dateList[index]
            this.getTrainingDayList()
        },
        // 导入历史模板
        handleChangeImport(value) {
            const currentWeek = this.$refs["cascaderCurrent"].getCheckedNodes()[0].pathLabels.join('-')
            const oldWeek = this.$refs["cascaderHistory"].getCheckedNodes()[0].pathLabels.join('-')
            let _this = this
            const queryObj = { oldWeekId: value[2], weekId: this.queryParams.weekId }
            this.$confirm('是否确认将' + ' "' + oldWeek + '" ' + '的训练项目' + '，' + '导入到' + ' "' + currentWeek + '" ' + '中？', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                return importTrainingWeek(queryObj).then((response) => {
                    this.modelValue = ''
                    // 等后台返回不同的状态码再优化，当前不管是什么状态后端返回的状态码都是200
                    if (response.code == 200) {
                        if (response.msg == '当前周已存在训练项目,无法复用') {
                            this.$message.error('当前周已存在训练项目,无法复用')
                        } else if (response.msg == '复用周无训练项目') {
                            this.$message.error('复用周无训练项目')
                        } else if (response.msg == '无效周') {
                            this.$message.error('无效周')
                        } else {
                            this.msgSuccess('导入成功！')
                        }
                    } else {
                        this.$message.error('导入计划请求失败')
                    }
                })
            }).then(() => {
                return this.getTrainingDayList()
            }).catch(() => {
                _this.modelValue = ''
            });

        },
        // 查询getNaturalYearTree列表,设置默认年/期/周三级联动的值,并获取weekId
        getNaturalYearTreeList() {
            getNaturalYearTree().then((response) => {
                this.treeList = this.getTreeData(response.data)

                const yearId = this.treeList[0].id,
                    cycleId = this.treeList[0].children[0].id,
                    weekId = this.treeList[0].children[0].children[0].id
                this.treeValue.push(yearId, cycleId, weekId)
                this.queryParams.weekId = weekId
            })
        },
        // 递归判断列表，把后台传的json最后的children设为删除
        getTreeData(data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].children == null) {
                    // children若为空数组，则将children设为undefined
                    delete data[i].children;
                } else {
                    // children若不为空数组，则继续 递归调用 本方法
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        /** 查询getTrainingWeekDetails详情 */
        getTrainingWeekDetails() {
            if (this.queryParams.weekId) {
                getTrainingWeek(this.queryParams.weekId).then((response) => {
                    this.form = response.data

                    // 同时日计划信息的默认日期为所选周的第一天的训练信息
                    this.dayQueryParams.day = this.form.startTime;
                    this.dateList = this.getBetweenDateStr(this.form.startTime, this.form.endTime)
                    this.getZhouList()
                    this.getTrainingDayList()
                    this.weekLoading = false;
                })
            }
        },
        // 周型字典翻译
        typeFormat(row, column) {
            return this.selectDictLabel(this.typeList, row.type);
        },
        //用户名称集合
        getSysUserList() {
            this.loading = true;
            listGetSysUser(this.queryParams).then((response) => {
                this.sysUserList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 周型集合
        getWeekTypeList() {
            this.loading = true;
            this.getDicts("week_type").then((response) => {
                this.typeList = response.data;
                this.loading = false;
            });
        },
        //训练地点集合
        getTrainingLocationList() {
            this.loading = true;
            listLocation(this.queryParams).then((response) => {
                this.trainingLocationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 查询trainingDayList列表
        getTrainingDayList() {
            this.loading = true;
            listTrainingDay(this.dayQueryParams).then(response => {
                this.trainingDayList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 根据日期查询当日训练列表
        handleQuery() {
            this.getTrainingDayList()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delTrainingDay(ids);
            }).then(() => {
                this.getTrainingDayList();
                this.msgSuccess("删除成功");
            }).catch(function () {
            });
        },
        // 新增训练计划
        handleAdd(row) {
            this.projectDialogVisible = true
            this.$refs.trainingProjectRef.handleAdd(this.dayQueryParams.weekId, this.dayQueryParams.day) // 传值weekId和day给子组件
        },
        // 查看按钮操作
        handleSee(row) {
            getTrainingDayInfo(row.id).then((response) => {
                this.$refs.groupChannelRef.handleSee(response.data)
            })
            this.groupChannelDialogVisible = true
        },
           // 查看课程要求
        handleCourse(row) {
            getTrainingDayInfo(row.id).then((response) => {
                this.$refs.courseRequireRef.handleCourse(response.data)
            })
            this.courseRequireDialogVisible = true
        },
        // 编辑按钮
        handleEdit(row) {
            this.projectDialogVisible = true
            this.$refs.trainingProjectRef.handleEdit(row)
        },
        // 点击保存按钮
        submitForm() {
            // 修改周计划详情
            this.weekLoading = true;
            updateTrainingWeek(this.form).then((response) => {
                if (response.code === 200) {
                    this.msgSuccess("保存成功");
                } else {
                    this.msgError(response.msg);
                }
                this.weekLoading = false;
            });
        },
    }
};
</script>
<style lang="scss" scoped>
.el-form--inline .el-form-item {
    margin: 10px 20px 10px 0;
    width: 300px;
}
.header-week {
    max-width: 600px;
}
.el-radio-group {
    display: flex;
    justify-content: space-around;
    padding: 10px 30px;
    background: #f2f6fc;
    border-radius: 10px;
    margin-bottom: 10px;
}

.header-title {
    color: #409eff;
    line-height: 33px;
    width: 200px;
}
.header-item {
    font-size: 14px;
    color: #606266;
    font-weight: 700;
    width: 380px;
    line-height: 33px;
}
.header-item2 {
    width: 200px;
}
.header-btn {
    width: 110px;
}
.saveBtn {
    width: 100px;
}
</style>